package top.hymsk.ecommerce.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.hymsk.ecommerce.pojo.response.GeneralResponse;
import top.hymsk.ecommerce.pojo.status.ResponseStatusCode;
import top.hymsk.ecommerce.utils.JwtUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


@Component
@Aspect
public class TokenAnalysisAspect {

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(top.hymsk.ecommerce.anno.TokenAnalysis)")
    public Object tokenAnalysis(ProceedingJoinPoint joinPoint) throws Throwable {
        //请求方法参数
        try {
            String token = request.getParameter("token");
            request.setAttribute("userId", JwtUtils.parseJwt(token).get("userId"));
            request.setAttribute("storeId", JwtUtils.parseJwt(token).get("storeId"));
        } catch (RuntimeException e) {
            return GeneralResponse.fail(ResponseStatusCode.AUTHENTICATION_FAILURE);
        }
        return joinPoint.proceed();
    }
}
